#!/bin/sh
# (C) James Budiono 2016
# License: GPL Version 3 or later
# $1-brightness in percent (0-100), or +/up or -/down or restore

FATDOG_STATE_DIR=$HOME/.config

### helper functions 
# $1-brightness
use_xbacklight() {
	xbacklight -set $1
}

# $1-brightness
use_sysfs() {
	[ -z "$DEVICE" ] && return 1
	read MAXVAL < $DEVPATH/$DEVICE/max_brightness
	VAL=$(( (MAXVAL * $1) / 100 ))
	echo $VAL > $DEVPATH/$DEVICE/brightness
}

# $1-brightness
save_settings() {
	touch $CTL
	sed -i -e '/.*BRIGHTNESS=.*/d' $CTL
	echo "BRIGHTNESS=$1" >> $CTL
}


### load config
if [ $(id -u) -eq 0 ]; then
	CTL=/etc/brightness.conf
else
	CTL=$FATDOG_STATE_DIR/brightness.conf
fi
test -r $CTL && . $CTL

# make sure variables aren't empty
DEVPATH=${DEVPATH:-/sys/class/backlight}
DEVICE=${DEVICE:-$(ls $DEVPATH | head -n 1)}
BRIGHTNESS=${BRIGHTNESS:-100}
STEPSIZE=${STEPSIZE:-10}
#USE_XBACKLIGHT=yes

##### main #####
case "$1" in
	+|up)   BRIGHTNESS=$((BRIGHTNESS + STEPSIZE)) ;;
	-|down) BRIGHTNESS=$((BRIGHTNESS - STEPSIZE)) ;;
	restore) ;; # use as specified in the settings
	[0-9]*) BRIGHTNESS=$1 ;; # as given
	"") case "$0" in
			*up)    BRIGHTNESS=$((BRIGHTNESS + STEPSIZE)) ;;
			*down)  BRIGHTNESS=$((BRIGHTNESS - STEPSIZE)) ;;
			*) echo "Usage: ${0##*/} percent-brightness|up|down|restore" && exit ;;
		esac ;;
esac

# ensure it is not out of range
[ $BRIGHTNESS -gt 100 ] && BRIGHTNESS=100
[ $BRIGHTNESS -lt 0 ] && BRIGHTNESS=0
#echo $BRIGHTNESS

# save new settings
save_settings $BRIGHTNESS

# now set brightness
if [ $(id -u) -eq 0 ] && [ -z "$USE_XBACKLIGHT" ]; then
	use_sysfs $BRIGHTNESS
else
	use_xbacklight $BRIGHTNESS
fi

